<?php namespace simpleFlow\database;

use simpleFlow\Object as SFObject;
use simpleFlow\File as SFFile;
use simpleFlow\error\Exception as SFException;

/**
 * Manage connections
 * @package simpleFlow
 * @subpackage database
 * @author Guilherme Fontenele
 */
class Connection extends SFObject
{
	/**
	 * @var resource Link
	 */
	private static $resLink = null;
	
	/**
	 * Constructor
	 */
	public function __construct()
	{
		self::$resLink = self::getLink();
	}
	
	/**
	 * Get the connection link
	 * @return resource Connection link
	 */
	public static function getLink()
	{
		if(self::$resLink) { return self::$resLink; }
		try
		{
			$strFile = \SF_APP_DIR_ROOT.'.configs/database.ini';
			if(SFFile::readable($strFile))
			{
				$arrParse = \parse_ini_file($strFile, true);
				if(\in_array($arrParse[\SF_ENV]['driver'],\PDO::getAvailableDrivers()))
				{
					$strDsn			= $arrParse[\SF_ENV]['driver'].':';
					$strUsername	= $arrParse[\SF_ENV]['username'];
					$strPassword	= $arrParse[\SF_ENV]['password'];

					$strDsn.= 'host='.$arrParse[\SF_ENV]['host'].';dbname='.$arrParse[\SF_ENV]['dbname'].';port='.$arrParse[\SF_ENV]['port'].';';
					
					self::$resLink = new \PDO($strDsn, $strUsername, $strPassword);
					self::$resLink->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
					return self::$resLink;
				}else{
					\trigger_error("Driver {$arrParse[\SF_ENV]['driver']} is not installed!");
				}
			}
		}
		catch(SFException $objException)
		{
			\trigger_error($objException->getMessage());
		}
	}
}

?>